package com.hs.jpademo1.controller;

import com.hs.jpademo1.entity.Student;
import com.hs.jpademo1.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @ClassName PageControlller
 * @Description TODO
 */
@Controller
public class PageControlller {
    @Autowired
    StudentService service;

    @GetMapping("/list")
    public String toList(HttpSession session, Model model,@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum){
        String path = isLogin(session,"list");
        Page<Student> page = service.findByPage(pageNum, 3);
        if("list".equals(path)){
           model.addAttribute("studentList",page.toList());
           model.addAttribute("total",page.getTotalPages());
           model.addAttribute("pageInfo",page);
        }
        return path;
    }

    @GetMapping("/update/{id}")
    public String toUpdate(HttpSession session, Model model,@PathVariable Integer id){
        String path = isLogin(session,"update");
        if("update".equals(path)){
            model.addAttribute("student",service.findById(id));
        }
        return path;
    }

    @GetMapping("/remove/{id}")
    public String remove(@PathVariable Integer id){
        int i = service.removeStudent(id);
        return "redirect:/list";
    }

    @GetMapping("/add")
    public String toAdd(HttpSession session, Model model){
        return isLogin(session,"add");
    }

    private String isLogin(HttpSession session,String path){
        if(session.getAttribute("user") == null){
            return "login";
        }
        return path;
    }

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }

    @GetMapping("/uploadFile")
    public String toUploadFile(){
        return "uploadFile";
    }

    @PostMapping("/condition")
    public String condition(Student student, Model model){
        Page<Student> page = service.findByCondition(0, 3, student);
        model.addAttribute("studentList",page.toList());
        model.addAttribute("total",page.getTotalPages());
        model.addAttribute("pageInfo",page);
        return "list";
    }
}
